#!/bin/bash
#
# https://github.com/Aniverse/inexistence
# Author: Aniverse

script_update=2020.11.18
script_version=r30027

################################################################################################ Debug

usage_for_debug() {
    export local_packages=/etc/inexistence/00.Installation
    export s=$local_packages/package/flexget/install
    rm -f $s ; nano $s ; bash $s
    bash <(wget -qO- https://github.com/Aniverse/inexistence/raw/master/00.Installation/package/flexget/install)
}

################################################################################################ Get options

unset LogRootPath LogTimes DebLocation SCLocation LOCKLocation OutputLOG \
      user

AppName=FlexGet
AppNameLower=flexget
Need_SourceCode=no
pm_action=install

function show_usage() { echo "
$AppName $pm_action $script_version ($script_update)
Usage:
      -l        Specifiy LogBase (Not log file)
      -d        Enable debug mode
      --log     Show logfile's content"
exit 1 ; }

OPTS=$(getopt -o u:v:l:d -al user:,version:,debug,logbase:,system,log -- "$@")
[ ! $? = 0 ] && show_usage
eval set -- "$OPTS"

while [ -n "$1" ] ; do case "$1" in
    -d | --debug        ) debug=1       ; shift   ;;
    -v | --version      ) version="$2"  ; shift 2 ;;
    -u | --user         ) user="$2"     ; shift 2 ;;
    -l | --logbase      ) LogTimes="$2" ; shift 2 ;;
         --system       ) unset user    ; shift   ;;
         --log          ) show_log=1    ; shift   ;;
    -- ) shift ; break ;;
esac ; done
# -v, -u and --system is deprecated currently

################################################################################################ Set Variables

if [[ -f /etc/inexistence/00.Installation/function ]]; then
    source /etc/inexistence/00.Installation/function
else
    source <(wget -qO- https://github.com/Aniverse/inexistence/raw/master/00.Installation/function)
fi

set_variables_log_location
check_var_OutputLOG
debug_log_location
cat_outputlog

################################################################################################



function patch_flexget() {
    # pypath=/usr/local/lib/python$(python3 -V | grep -oE "3.[0-9]")/dist-packages
    # Debian 9, /usr/local/lib/python3.7/site-packages
    pypath=$($python_cmd -m site 2>&1 | grep package | head -1 | cut -d \' -f2)  # /opt/venv/flexget/lib/python3.7/site-packages
    mkdir -p /tmp
    cat << EOF > /tmp/flexget-remove-passwd-check.patch
diff -Nur flexget/webserver.py flexget-patch/webserver.py
--- webserver.py	2020-02-28 11:50:07.423005342 +0800
+++ webserver.py	2020-02-28 11:57:52.831474088 +0800
@@ -241,6 +241,7 @@
 @with_session
 def change_password(username='flexget', password='', session=None):
     check = zxcvbn.zxcvbn(password, user_inputs=[username])
+    check['score'] = 4
     if check['score'] < 3:
         warning = check['feedback']['warning']
         suggestions = ' '.join(check['feedback']['suggestions'])
EOF
    patch -d ${pypath}/flexget/ < /tmp/flexget-remove-passwd-check.patch >> "$OutputLOG" 2>&1
    $python_cmd -m compileall ${pypath}/flexget/webserver.py >> "$OutputLOG" 2>&1
    rm -f /tmp/flexget-remove-passwd-check.patch
}


function install_python37() {
    pyenv_install_python 3.7.8
    pyenv_init_venv      3.7.8   /opt/venv/flexget
    python_getpip        3.7.8   /opt/venv/flexget
    pip_cmd="/opt/venv/flexget/bin/pip"
    python_cmd="/opt/venv/flexget/bin/python"
    flexget_cmd="/opt/venv/flexget/bin/flexget"
}



function install_flexget3() {

    echo >> $OutputLOG

    $pip_cmd install --upgrade setuptools                         >> "$OutputLOG" 2>&1 # 45.3.0
    $pip_cmd install --upgrade pyopenssl                          >> "$OutputLOG" 2>&1
    $pip_cmd install --upgrade cryptography                       >> "$OutputLOG" 2>&1
    $pip_cmd install --ignore-installed flexget==3.1.77           >> "$OutputLOG" 2>&1 # 3.0.31
    # For establishing connection with Deluge and Transmission client
    $pip_cmd install deluge-client transmissionrpc                >> "$OutputLOG" 2>&1
    # https://github.com/jerrymakesjelly/autoremove-torrents
    $pip_cmd install autoremove-torrents                          >> "$OutputLOG" 2>&1

    # For third-party plugin flexget_qbittorrent_mod
    # https://github.com/IvonWei/flexget_qbittorrent_mod/wiki
    # $pip_cmd install brotli baidu-aip pillow python-Levenshtein  >> "$OutputLOG" 2>&1
    # $pip_cmd install pandas matplotlib fuzzywuzzy                >> "$OutputLOG" 2>&1 # selenium
    # $pip_cmd install python-telegram-bot==12.8                   >> "$OutputLOG" 2>&1

    rm -f /usr/local/bin/flexget                                  >> "$OutputLOG" 2>&1
    rm -f /usr/local/bin/autoremove-torrents                      >> "$OutputLOG" 2>&1
    ln -s  $local_packages/package/flexget/ffgg    $local_script  >> "$OutputLOG" 2>&1
    ln -s /opt/venv/flexget/bin/flexget  /usr/local/bin/flexget   >> "$OutputLOG" 2>&1
    ln -s /opt/venv/flexget/bin/autoremove-torrents \
          /usr/local/bin/autoremove-torrents                      >> "$OutputLOG" 2>&1

    patch_flexget
    _execute "$flexget_cmd -V" # for debug

    status_lock=$AppNameLower
    echo "status_lock=$status_lock" > /tmp/Variables
    rm -f /tmp/$status_lock.1.lock /tmp/$status_lock.2.lock
    flexget_ver=$($flexget_cmd -V 2>&1 | head -1)
    if [[ -n $flexget_ver ]] && version_ge $flexget_ver 3.1.66 ; then
        touch /tmp/$status_lock.1.lock
    else
        touch /tmp/$status_lock.2.lock
    fi
    [[ -f /tmp/$status_lock.1.lock ]] && touch $LOCKLocation/$AppNameLower.lock
    echo >> $OutputLOG

}



################################################################################################


if [[ ! -f $LOCKLocation/pyenv.lock ]]; then
    bash <(wget -qO- https://github.com/Aniverse/inexistence/raw/master/00.Installation/package/pyenv)
fi

install_python37

echo_task "Installing $AppName ..."
install_flexget3 & spinner $!
check_status $status_lock

[[ $debug == 1 ]] && which flexget


################################################################################################ Deprecated


function deprecated_codes_backup_here() {
    if [[ "$CODENAME" =~ (jessie|stretch) ]]; then
        sed -i "s/\/usr\/bin\/python3/\/usr\/local\/bin\/python3.7/g" /usr/local/bin/flexget
        sed -i "s/\/usr\/bin\/python3/\/usr\/local\/bin\/python3.7/g" /usr/local/bin/flexget-headless
        update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.4        2  >> "$OutputLOG" 2>&1        # Debian 8 jessie
        update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.5        2  >> "$OutputLOG" 2>&1        # Debian 9 stretch
        update-alternatives --install /usr/bin/python3 python3 /usr/local/bin/python3.7  1  >> "$OutputLOG" 2>&1
    fi
}


function install_flexget2_user() {
    echo >> $OutputLOG

    apt_install_check    python python-dev python-pip
    apt_install_separate
    python2 -m pip install --upgrade pip >> "$OutputLOG" 2>&1
    python2 -m pip install pathlib >> "$OutputLOG" 2>&1
    python2 -m pip install transmissionrpc deluge-client >> "$OutputLOG" 2>&1

    if [[ -z $user ]]; then
        python2 -m pip install flexget >> "$OutputLOG" 2>&1
    else
        su $user -c 'python2 -m pip install flexget --user' >> "$OutputLOG" 2>&1
        export PATH=/home/$user/.local/bin:$PATH
    fi

    status_lock=$AppNameLower
    echo "status_lock=$status_lock" > /tmp/Variables
    rm -f /tmp/$status_lock.1.lock /tmp/$status_lock.2.lock 
    which flexget > /dev/null && touch /tmp/$status_lock.1.lock || touch /tmp/$status_lock.2.lock
    [[ -f /tmp/$status_lock.1.lock ]] && touch $LOCKLocation/$AppNameLower.lock
    echo >> $OutputLOG
}
